package org.example.config;

import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import sun.misc.BASE64Encoder;

/**
* @description: TODO
* @author 杨镇宇
* @date 2024/8/29 17:17
* @version 1.0
*/
@Configuration
public class EsBConfig {

    @Value("${es.b.ip}")
    private String esIp;
    @Value("${es.b.port}")
    private String esPort;
    @Value("${es.b.user}")
    private String esUser;
    @Value("${es.b.passWord}")
    private String esPassWord;

    public RestHighLevelClient getHighLevelClient(){
        RestHighLevelClient restHighLevelClient = null;
        if (ObjectUtil.isNotEmpty(esIp) && ObjectUtil.isNotEmpty(esPort)){
            RestClientBuilder builder = RestClient.builder(new HttpHost(esIp,Integer.parseInt(esPort),"http"))
                    .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                        @Override
                        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                            return httpAsyncClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
                                    .setConnectTimeout(30000)
                                    .setSocketTimeout(30000)
                                    .build()
                            );
                        }
                    });
            restHighLevelClient = new RestHighLevelClient(builder);
        }
        return restHighLevelClient;
    }

    public RequestOptions getRequestOptions(){
        RequestOptions requestOptions = null;
        if (ObjectUtil.isNotEmpty(esUser) && ObjectUtil.isNotEmpty(esPassWord)) {
            String msg =  StringUtils.join(esUser, "@", esPassWord);
            String encode = new BASE64Encoder().encode(msg.getBytes());
            RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
            builder.addHeader("Authorization","Bearer "+encode);
            requestOptions = builder.build();
        }
        return requestOptions;
    }
}
